﻿using AVCJobDispatcherLinux.TaskJobEngine;
using HelperLibrary;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace AVCJobDispatcherLinux
{
    /// <summary>
    /// 任务宿主服务
    /// </summary>
    class JobHostedService : IHostedService
    {
        /// <summary>
        /// 生命周期
        /// </summary>
        private readonly IHostApplicationLifetime _applicationLifetime;

        /// <summary>
        /// 构造
        /// </summary>
        public JobHostedService(IHostApplicationLifetime applicationLifetime)
        {
            _applicationLifetime = applicationLifetime;
        }

        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task StartAsync(CancellationToken cancellationToken)
        {
            return Task.Run(() =>
            {
                _applicationLifetime.ApplicationStarted.Register(() =>
                {
                    string path = Path.Combine(Directory.GetCurrentDirectory(), "TaskJob.json");
                    var builder = new ConfigurationBuilder().AddJsonFile(path, false, true);
                    var dbConfig = builder.Build();
                    TaskJobManager.Start(dbConfig);
                    LogHelper.LogDebug("Job dispatcher started!");
                });
                _applicationLifetime.ApplicationStopped.Register(() =>
                {
                    LogHelper.LogDebug("Job dispatcher stopped!");
                });
            });
        }

        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
